#!bin/bash

#Desc:install openresty by soucre 
#Author:zhang huan
#Create:2020-09-16
#Update:
#Usage:

#source package path
sourcePath=$1
#unpack path
unpackPath=openresty

#instart Rely software 
yum install   pcre-devel zlib-devel openssl-devel -y 

#create user for openresty
useradd -r -s /sbin/nologin www  &>/dev/null

#unpack source package
mkdir $unpackPath
tar -zxf  $sourcePath  -C $unpackPath

#go to directory path
cd $unpackPath/*/

#configure ,make and make install 
./configure --prefix=/usr/local/openresty \
--user=www --group=www --with-http_ssl_module \
--with-http_stub_status_module \
--with-http_realip_module && make && make install

#create a lua script for server  to prevent malicious attacks
mkdir /usr/local/lua
cat > /usr/local/lua/access_limit.lua << EOF
local function close_redis(red)
    if not red then
        return
    end
    local pool_max_idle_time = 10000
    local pool_size = 100
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
 
    if not ok then
        ngx_log(ngx_ERR, "set redis keepalive error : ", err)
    end
end
 
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ip = "192.168.1.36" -- redis ip
local port = 6379 -- redis port
local ok, err = red:connect(ip,port)
red:auth("123") -- redis auth password
if not ok then
    return close_redis(red)
end
 
local clientIP = ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
   clientIP = ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
   clientIP = ngx.var.remote_addr
end
 
local incrKey = "user:"..clientIP..":freq"
local blockKey = "user:"..clientIP..":block"
 
local is_block,err = red:get(blockKey) -- check if ip is blocked
if tonumber(is_block) == 1 then
   ngx.exit(ngx.HTTP_FORBIDDEN) -- return 403
   return close_redis(red)
end
 
res, err = red:incr(incrKey)
 
if res == 1 then
   res, err = red:expire(incrKey,1)
end
 
if res > 5 then	-- block
    res, err = red:set(blockKey,1)
    res, err = red:expire(blockKey,600)
end
 
close_redis(red)
EOF